<template>
	<view>
		<view class="mar_top70 mar_bottom70">
			<button class="avatar-wrapper" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
				<image class="avatar" :src="avatarUrl" mode=""></image>
			</button>
		</view>
		<view class="nick-name flex align-center">
			<view class="label fontS26 color_222222">昵称</view>
			<input type="nickname" class="weui-input" v-model="username" placeholder="请输入昵称" @blur="bindblur" />
		</view>

		<u-tabbar fixed placeholder safeAreaInsetBottom>
			<view @tap="onSave" class="save flex align-center justify-center">保存</view>
		</u-tabbar>
	</view>
</template>

<script setup>
	import {
		ref,
		getCurrentInstance
	} from 'vue';

	import {
		onLoad
	} from '@dcloudio/uni-app';

	import {
		uploadFile
	} from '@/utils/common.js';

	const {
		proxy
	} = getCurrentInstance();

	const avatarUrl = ref();
	const username = ref('');
	const formData = ref({
		uuid: '',
		url: ''
	});
	// 上传头像
	const onChooseAvatar = (e) => {
		uploadFile(e.detail.avatarUrl).then(res => {
			formData.value = JSON.parse(res.data).data ? JSON.parse(res.data).data : formData.value
			avatarUrl.value = JSON.parse(res.data).data.url
		}).catch(err => {
			uni.showToast({
				title: '上传失败，请重试~',
				icon: 'none',
				duration: 2000
			})
		})
	}

	// 昵称
	const bindblur = (e) => {
		username.value = e.detail.value
	}

	// 保存
	const onSave = () => {
		const userInfo = JSON.parse(uni.getStorageSync('user_info'));
		proxy.$api.updateUser({
			avatarUuid: formData.value.uuid,
			userProfileImg: formData.value.url,
			username: username.value,
			uuid: userInfo.user.uuid,
		}).then(res => {
			uni.showToast({
				title: '操作成功'
			})
			setTimeout(() => {
				uni.navigateBack();
			}, 1200)
		})
	}

	onLoad(() => {
		const userInfo = JSON.parse(uni.getStorageSync('user_info'))
		username.value = userInfo.user.username;
		avatarUrl.value = userInfo.user.userProfileImg;
	})
</script>

<style lang="scss" scoped>
	.avatar {
		width: 120rpx;
		height: 120rpx;
		border-radius: 4rpx;
	}

	.avatar-wrapper {
		background: none;
		border: none;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	button::after {
		border: none;
	}

	.nick-name {
		padding: 0 30rpx;
		height: 100rpx;
		border-top: 1rpx solid #eee;
		border-bottom: 1rpx solid #eee;

		.label {
			width: 150rpx;
		}

		.weui-input {
			flex: 1;
			color: #222222;
			font-size: 28rpx;
		}
	}

	.save {
		margin-top: 20rpx;
		width: 720rpx;
		height: 80rpx;
		color: #fff;
		font-size: 32rpx;
		border-radius: 8rpx;
		background: #E5725F;
	}
</style>
